package cn.fx.baseweb.controller;

import cn.fx.framework.utils.ReturnResult;
import cn.fx.framework.web.Http5Util;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder;
import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import org.apache.hc.client5.http.impl.async.HttpAsyncClients;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.core5.concurrent.FutureCallback;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import static cn.fx.framework.web.Http5Util.post;

/**
 * 测试Http5Utils.get,Http5Utils.post,异步调用
 */
@RestController
@RequestMapping("/testhttputils")
public class TestHttpUtilsController {


    /**
     * @RequestBody将表单提交的数据直接转换成一个对象，如：User、Role
     * @param req
     * @return
     */
    @PostMapping("/post")
    public ReturnResult testPost(@RequestBody Object req) {
        ReturnResult returnResult = new ReturnResult();
        String url = "http://xxx.com.cn";
        try {
            // 1、构建入参、添加 headers
            StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(req), ContentType.APPLICATION_JSON);
            Map<String, String> headers = new HashMap<>();

            // 2、发起http请求
            CloseableHttpResponse httpResponse = Http5Util.post(url, "POST",headers, stringEntity);

            // 3、返回结果，异常处理
            returnResult.setCode(httpResponse.getCode());
            returnResult.setMessage(httpResponse.getReasonPhrase());
            if (httpResponse.getCode() == 200) {
                String resStr = EntityUtils.toString(httpResponse.getEntity());
                returnResult.setData(resStr);
            } else {
            }
        } catch (Exception e) {
            returnResult.setMessage(e.getMessage());
        }
        return returnResult;
    }

    /**
     * 上传文件,并将文件上传到另一个服务器
     *
     * @param multipartFile
     * @param token
     * @param key
     * @return
     */
    @PostMapping("uploadFile")
    public ReturnResult testPostFile(@RequestParam("file") MultipartFile multipartFile, @RequestParam("token") String token, @RequestParam("key") String key) {
        ReturnResult returnResult = new ReturnResult();
        String url = "http://xxx.com.cn";
        try {
            // 1、构建File参数
            File file = new File(multipartFile.getOriginalFilename());
            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(multipartFile.getBytes());
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, "ex.xlsx");

            // 2、构建其他参数
            builder.addTextBody("token", token, ContentType.TEXT_PLAIN);
            builder.addTextBody("key", key, ContentType.TEXT_PLAIN);
            HttpEntity multipartEntity = builder.build();

            // 3、需要加 header，在这里加
            Map<String, String> headers = new HashMap<>();

            // 4、发起http请求
            CloseableHttpResponse httpResponse = post(url, "POST", headers, multipartEntity);
            // 5、返回结果，异常处理
            returnResult.setCode(httpResponse.getCode());
            returnResult.setMessage(httpResponse.getReasonPhrase());
            if (httpResponse.getCode() == 200) {
                String resStr = EntityUtils.toString(httpResponse.getEntity());
                returnResult.setData(resStr);
            } else {
            }
        } catch (Exception e) {
            returnResult.setMessage(e.getMessage());
        }
        return returnResult;
    }

    /**
     * 测试异步调用服务器
     */
    @GetMapping("testAsync")
    public void testAsync(){

    CloseableHttpAsyncClient asyncClient = Http5Util.httpAsyncClient;

    asyncClient.start();

    SimpleHttpRequest simpleHttpRequest = new SimpleHttpRequest("GET",URI.create("https://jsonplaceholder.typicode.com/posts/1"));
    asyncClient.execute(simpleHttpRequest, new FutureCallback<>() {
        @Override
        public void completed(SimpleHttpResponse simpleHttpResponse) {
            System.out.println("Response received: " + simpleHttpResponse.getCode());
        }

        @Override
        public void failed(Exception ex) {
            System.out.println("Request failed: " + ex.getMessage());
        }

        @Override
        public void cancelled() {
            System.out.println("Request cancelled");
        }
    });

}


}
